import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/store'
// import * as types from '../store/types'
import Home from '@/components/Home'
import TodoList from '@/components/TodoList'
import Login from '@/components/login'
import ui from '@/components/ui'
import toolbar from '@/components/ui.toolbar'
import vuetifyToolbar from '@/components/vuetify/toolbar'
import fetch from '@/components/fetch'
import comment from '@/components/comment'
Vue.use(Router)

const router = new Router({
  mode: 'hash', // history
  routes: [
    {
      path: '/',
      name: '主页',
      component: Home
    },
    {
      path: '/login',
      name: '登录',
      component: Login
    },
    {
      path: '/todoList',
      name: 'todoList',
      component: TodoList
    },
    {
      path: '/ui',
      name: 'ui',
      component: ui
    },
    {
      path: '/ui/toolbar',
      name: 'toolbar',
      component: toolbar,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/ui/vuetify/toolbar',
      name: 'vuetifyToolbar',
      component: vuetifyToolbar
    },
    {
      path: '/fetch',
      name: 'fetch',
      component: fetch
    },
    {
      path: '/comment',
      name: 'comment',
      component: comment
    }
  ]
})

// if (window.localStorage.getItem('token')) {
//   store.commit(types.LOGIN, window.localStorage.getItem('token'))
// }

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (store.state.token) {  // 通过vuex state获取当前的token是否存在
      next()
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})
export default router
